import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

const API_URL = 'http://localhost:3000/api'

export const useBillsStore = defineStore('bills', () => {
  const bills = ref([])
  const currentBill = ref(null)
  const loading = ref(false)
  const pagination = ref({
    total: 0,
    page: 1,
    limit: 20,
    pages: 1
  })

  const fetchBills = async (page = 1, limit = 20) => {
    loading.value = true
    try {
      const response = await axios.get(`${API_URL}/bills`, {
        params: { page, limit }
      })
      
      bills.value = response.data.bills
      pagination.value = response.data.pagination
    } catch (error) {
      console.error('获取账单失败:', error)
    } finally {
      loading.value = false
    }
  }

  const fetchBill = async (id) => {
    loading.value = true
    try {
      const response = await axios.get(`${API_URL}/bills/${id}`)
      currentBill.value = response.data
    } catch (error) {
      console.error('获取账单详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  const createBill = async (billData) => {
    try {
      const response = await axios.post(`${API_URL}/bills`, billData)
      await fetchBills()
      return { success: true, data: response.data }
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || '创建账单失败'
      }
    }
  }

  const updateBill = async (id, billData) => {
    try {
      const response = await axios.put(`${API_URL}/bills/${id}`, billData)
      await fetchBills()
      return { success: true, data: response.data }
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || '更新账单失败'
      }
    }
  }

  const deleteBill = async (id) => {
    try {
      await axios.delete(`${API_URL}/bills/${id}`)
      await fetchBills()
      return { success: true }
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || '删除账单失败'
      }
    }
  }

  return {
    bills,
    currentBill,
    loading,
    pagination,
    fetchBills,
    fetchBill,
    createBill,
    updateBill,
    deleteBill
  }
})
